﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Filters;
using Ttifa.Log;
using Ttifa.Infrastructure.Utils;

namespace Ttifa.WebApiBase.Filters
{
    public class ApiErrorAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            // 取消操作不记录日志
            if (actionExecutedContext.Exception is OperationCanceledException)
            {
                actionExecutedContext.Response = ApiResult.Response(ApiStatus.Fail, $"{actionExecutedContext.Exception.Message}");
                return;
            }

            var dict = new Dictionary<string, object>();
            var requestUri = actionExecutedContext.Request.RequestUri;
            dict.Add("IP", IPHelper.GetRequestIP());
            dict.Add("Url", requestUri.AbsoluteUri);
            dict.Add("Method", actionExecutedContext.Request.Method);
            var param = actionExecutedContext.ActionContext.ActionArguments;
            if (param.Count > 0)
            {
                dict.Add("Params", param);
            }
            dict.Add("Result", actionExecutedContext.Exception.Message);
            LogFactory.GetLogger().SetProperties(dict).Error(requestUri.AbsolutePath, actionExecutedContext.Exception);

            actionExecutedContext.Response = ApiResult.Response(ApiStatus.Fail, actionExecutedContext.Exception.Message);
        }
    }
}